package com.goodomen.garbage.common.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.util.Map;

/**
 * 真实 IP 信息
 */
public class IpUtils {

	protected final static Logger LOG = LoggerFactory.getLogger(IpUtils.class);
	
	private static final String CHINAZ_URL = "http://tool.chinaz.com/ip/?IP=";
	private static final String TAOBAO_URL = "http://ip.taobao.com/service/getIpInfo.php?ip=";

	/** 太平洋 */
	private static final String PC_ONLINE = "http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=";
	/** 国外 */
	private static final String IP_API = "http://ip-api.com/json/var?lang=zh-CN";


	/**
	 * 查询ip信息
	 * @param ip
	 * @return
	 */
	public static String getIpInfo(String ip) {
		if (StringUtils.isBlank(ip))
			return null;
		
		String address = getPcOnline(ip);
		if(StringUtils.isBlank(address)){
			address = getIpApi(ip);
		}
		return address;
	}
	
	/**
	 * 使用Chinaz接口查询ip信息
	 * http://tool.chinaz.com/ip/?IP=[ip地址字串] 
	 * @param ip
	 * @return
	 */
	public static String getChinazIp(String ip) {
		if (StringUtils.isBlank(ip))
			return null;
		
		try {
			long st = System.currentTimeMillis();
			Document doc = Jsoup.parse(new URL(CHINAZ_URL + ip), 1500);
			Elements els = doc.select("span[id=status]").select("strong[class=red]");
			if (LOG.isDebugEnabled()) {
				LOG.debug("Chinaz IP库未查询到IP：(" + ip + "),url验证ip耗时：" + (System.currentTimeMillis() - st) + "ms");
			}
			if (els != null && !els.isEmpty()) {
				String MARK = "==>>";
				String info = els.text();
				return info.substring(info.lastIndexOf(MARK) + MARK.length()).trim();
			}
		} catch (Exception e) {
			LOG.error("Chinaz IP库查询异常", e);
		}
		return null;
	}
	
	/**
	 * 使用淘宝接口查询ip信息
	 * http://ip.taobao.com/service/getIpInfo.php?ip=[ip地址字串] 
	 * {"code":0,"data":{"ip":"210.75.225.254","country":"\u4e2d\u56fd","area":"\u534e\u5317","region":"\u5317\u4eac\u5e02","city":"\u5317\u4eac\u5e02","county":"","isp":"\u7535\u4fe1","country_id":"86","area_id":"100000","region_id":"110000","city_id":"110000","county_id":"-1","isp_id":"100017"}}
	 * @param ip
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static String getTaobaoIp(String ip) {
		if (StringUtils.isBlank(ip)) {
			return null;
		}
		
		try {
			String urls = TAOBAO_URL + ip;
			long st = System.currentTimeMillis();
			String result = HttpUtils.postRequest(urls, null, HttpUtils.UTF_8);
			if(StringUtils.isBlank(result)) {
				if (LOG.isDebugEnabled()) {
					LOG.debug("淘宝IP库未查询到IP：(" + ip + ")");
				}
				return null;
			}
			ObjectMapper objectMapper = new ObjectMapper();
			Map<String, Object> json = objectMapper.readValue(result, Map.class);
			if (LOG.isDebugEnabled()) {
				LOG.debug("查询淘宝接口，返回的JSON是:" + json);
			}
			
			Integer code = (Integer)json.get("code");
			if(code.intValue() != 0){
				if (LOG.isDebugEnabled()) {
					LOG.debug("淘宝IP库查询失败，IP：(" + ip + ")");
				}
				return null;
			}
			
			Map<String, String> data = (Map<String, String>) json.get("data");
			String country = data.get("country");
			String region = data.get("region");
			String city = data.get("city");
			String isp = data.get("isp");
			String address = "";
			if (StringUtils.isBlank(region) || StringUtils.isBlank(city))
				address = country;
			address = address + region + city + " " + isp;
			if (LOG.isDebugEnabled()) {
				LOG.debug("Taobao 查询到IP：(" + ip + "), 耗时：" + (System.currentTimeMillis() - st) + "ms");
			}
			return address.trim();
		} catch (Exception e) {
			LOG.error("淘宝IP库查询异常", e);
		}
		return null;
	}

	public static String getPcOnline(String ip) {
		if (StringUtils.isBlank(ip)) {
			return null;
		}

		try {
			String urls = PC_ONLINE + ip;
			long st = System.currentTimeMillis();
			String result = HttpUtils.postRequest(urls, null, HttpUtils.GB2312);
			if(StringUtils.isBlank(result)) {
				if (LOG.isDebugEnabled()) {
					LOG.debug("Pconline IP库未查询到IP：(" + ip + ")");
				}
				return null;
			}
			ObjectMapper objectMapper = new ObjectMapper();
			Map<String, Object> json = objectMapper.readValue(result, Map.class);
			if (LOG.isDebugEnabled()) {
				LOG.debug("查询Pconline接口，返回的JSON是:" + json);
			}

			String regionCode = (String)json.get("regionCode");

			if(Integer.valueOf(regionCode) != 0){
				if (LOG.isDebugEnabled()) {
					LOG.debug("Pconline IP库查询失败，IP：(" + ip + ")");
				}
				return null;
			}
			String pro = (String)json.get("pro");
			String region = (String)json.get("region");
			String city = (String)json.get("city");
			String addr = (String)json.get("addr");
			String address = "";
			address = address + addr;
			if (LOG.isDebugEnabled()) {
				LOG.debug("Pconline 查询到IP：(" + ip + "), 耗时：" + (System.currentTimeMillis() - st) + "ms");
			}
			return address.trim();
		} catch (Exception e) {
			LOG.error("Pconline IP库查询异常", e);
		}
		return null;
	}

	public static String getIpApi(String ip) {
		if (StringUtils.isBlank(ip)) {
			return null;
		}

		try {
			String urls = IP_API.replaceAll("var", ip);
			long st = System.currentTimeMillis();
			String result = HttpUtils.postRequest(urls, null, HttpUtils.UTF_8);
			if(StringUtils.isBlank(result)) {
				if (LOG.isDebugEnabled()) {
					LOG.debug("Pconline IP库未查询到IP：(" + ip + ")");
				}
				return null;
			}
			ObjectMapper objectMapper = new ObjectMapper();
			Map<String, Object> json = objectMapper.readValue(result, Map.class);
			if (LOG.isDebugEnabled()) {
				LOG.debug("查询Pconline接口，返回的JSON是:" + json);
			}

			String status = (String)json.get("status");

			if(!"success".equals(status)){
				if (LOG.isDebugEnabled()) {
					LOG.debug("Pconline IP库查询失败，IP：(" + ip + ")");
				}
				return null;
			}
			String country = (String)json.get("country");
			String region = (String)json.get("region");
			String city = (String)json.get("city");
			String isp = (String)json.get("isp");
			String address = "";
			if (StringUtils.isBlank(region) || StringUtils.isBlank(city))
				address = country;
			address = address  + city + " " + isp;
			if (LOG.isDebugEnabled()) {
				LOG.debug("Pconline 查询到IP：(" + ip + "), 耗时：" + (System.currentTimeMillis() - st) + "ms");
			}
			return address.trim();
		} catch (Exception e) {
			LOG.error("Pconline IP库查询异常", e);
		}
		return null;
	}
	
	public static void main(String[] args) {
		System.out.println(getPcOnline("14.16.139.216"));
		System.out.println(getIpApi("14.16.139.216"));
	}
	
}
